import { validNumberFromGet } from "../functionFromexport.js";

const logOutButton = document.getElementById("logOut");

const displayName = document.getElementById("clientNameProfile");
const circleName = document.getElementById("profileImg");
const displayId = document.getElementById("clienIdProfile");
const lessonsMinutes = document.getElementById("lessonsMinutes");
const clientVisit = document.getElementById("clientVisit");
const amountAvarage = document.getElementById("amountAvarage");
const bonusesGet = document.getElementById("bonusesGet");

let clientPhone = localStorage.getItem("phoneNumber");

const WebApp = window.Telegram.WebApp;
WebApp.BackButton.hide();

// let chatId = WebApp.initDataUnsafe.user.id; // id чата tg клиента
let chatId = "456072370";

clientPhone = validNumberFromGet(clientPhone);

// WebApp.BackButton.hide();
// // WebApp.onEvent("backButtonClicked", function () {
// //   history.back();
// //   WebApp.BackButton.hide();
// // });

fetch("/client", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    chatId: chatId,
    clientPhone: clientPhone,
  }),
})
  .then((response) => response.json())
  .then((data) => {
    displayClienName(data);
  })
  .catch((err) => {
    console.log(err);
  });

const displayClienName = (amount) => {
  amount.forEach(
    (
      {
        client_name,
        client_group_id_wout_letter,
        amount_average,
        bonuses_get,
        lessons_minutes,
        client_visit_count,
      },
      index
    ) => {
      if (index === 0) {
        if (client_name !== undefined) {
          const match = client_name.match(/(?<=)[А-Яа-яa-zA-Z]+$/g);

          displayName.innerText = match[0];
          circleName.innerText = match[0].slice(0, 1);
          displayId.innerText = client_group_id_wout_letter;
          lessonsMinutes.innerText = `${lessons_minutes} мин`;
          clientVisit.innerText = `${client_visit_count}`;
          amountAvarage.innerText = `${amount_average} мин`;
          bonusesGet.innerText = bonuses_get;
        }
      }
    }
  );
};

//Выход из ЛК
logOutButton.addEventListener("click", () => {
  localStorage.setItem("clientGroupId", "n/a");
  localStorage.setItem("phoneNumber", "n/a");
  fetch("/client", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      clientGroupId: "n/a",
      phoneNumber: "n/a",
    }),
  })
    .then((res) => res.json())
    .then((data) => {})
    .catch((err) => {
      console.log(err);
    });

  window.location.href = "/index.html";
});
